<template>
  <div class="page-container">
    <!--面包屑导航-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>营销中心</el-breadcrumb-item>
        <el-breadcrumb-item>其他类促销</el-breadcrumb-item>
        <el-breadcrumb-item>秒杀</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size" ref="filters" :rules="filtersRules">
        <el-row class="search-input">
          <el-form-item label="活动名称：" prop="promName">
            <el-input v-model="filters.promName" placeholder="活动名称" clearable maxlength="80"></el-input>
          </el-form-item>
          <el-form-item label="活动ID：" prop="promotionCode">
            <el-input v-model="filters.promotionCode" placeholder="活动ID" clearable maxlength="80"></el-input>
          </el-form-item>
          <!-- <el-form-item label="活动类型：" prop="frontPromType">
            <el-select v-model="filters.frontPromType" placeholder="全部">
              <el-option
                v-for="item in frontPromTypes"
                :key="item.type"
                :label="item.name"
                :value="item.type"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="创建人：" prop="creatorNameForSearch">
            <el-input v-model="filters.creatorNameForSearch" placeholder="创建人" clearable maxlength="80"></el-input>
          </el-form-item>
<!--          <el-form-item label="渠道：" prop="channelId">-->
<!--            <el-select v-model="filters.channelId" placeholder="全部" clearable>-->
<!--              <el-option-->
<!--                v-for="item in channelOption"-->
<!--                :key="item.id"-->
<!--                :label="item.channelName"-->
<!--                :value="item.id"-->
<!--              ></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->

<!--          <el-form-item label="活动商家：" prop="merchantId" v-if="false">-->
<!--            <el-select-->
<!--              v-model="filters.merchantId"-->
<!--              placeholder="活动商家"-->
<!--              @change="changeMerchant"-->
<!--              clearable-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in merchantIds"-->
<!--                :key="item.merchantId"-->
<!--                :label="item.label"-->
<!--                :value="item.merchantId"-->
<!--              ></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="活动店铺：" prop="storeId" v-if="false">-->
<!--            <el-select v-model="filters.storeId" placeholder="活动店铺" clearable>-->
<!--              <el-option-->
<!--                v-for="item in storeIds"-->
<!--                :key="item.storeId"-->
<!--                :label="item.label"-->
<!--                :value="item.storeId"-->
<!--              ></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-row class="times">
            <el-form-item label="活动时间：" prop="startTime">
              <el-date-picker
                v-model="filters.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="开始时间"
                class="input_postion"
                clearable
                @change="changeStartDate"
                :picker-options="startDateDisabled"
              ></el-date-picker>
            </el-form-item>
            <span class="times-to">-</span>
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="filters.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="结束时间"
                class="input_postion"
                @change="changeEndDate"
                :picker-options="endDateDisabled"
              ></el-date-picker>
            </el-form-item>
          </el-row>
        </el-row>
        <el-row class="search-button">
          <el-form-item>
            <kt-button :label="$t('action.reset')" class="resetButton" icon="el-icon-refresh" @click="resetForm('filters')" />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="el-icon-search" label="搜索"
              @click="getPromotionList()"
              class="searchButton"
            />
          </el-form-item>

          <el-form-item>
            <kt-button label="创建活动" @click="createPage()"  class="searchButton" />
          </el-form-item>
          <el-form-item>
            <kt-button label="通过模板添加活动" @click="useTemp()" perms="market:seckill:temp" class="searchButton" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="tab-container">
      <el-tabs v-model="activeName">
        <el-tab-pane
          v-for="item in tabMapOptions"
          :key="item.key"
          :label="item.label"
          :name="item.key"
        >
          <keep-alive>
            <tab-pane
              v-if="activeName==item.key"
              :type="item.key"
              ref="child"
              :parentFilters="filters"
              v-on:SecondSell="SecondSell"
            />
          </keep-alive>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!--弹出框-->
    <el-dialog title="请选择秒杀/拼团/秒杀形式" :visible.sync="flag" class="el-dialog-form">
      <div class="flex mb20">
        <p class="form-left-width">活动类型：</p>
        <el-select v-model="form.region" placeholder="请选择秒杀/拼团/秒杀形式">
          <el-option label="秒杀" value="one"></el-option>
          <el-option label="拼团" value="two"></el-option>
          <el-option label="秒杀" value="three"></el-option>
        </el-select>
      </div>
      <div class="flex mb20">
        <p class="form-left-width">当前参与用户：</p>
        <el-checkbox-group v-model="joinCheck">
          <el-checkbox v-for="item in joinList" :label="item" :key="item" class="mr20"></el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="flex mb20">
        <p class="form-left-width">推送方式：</p>
        <el-checkbox-group v-model="wayCheck">
          <el-checkbox v-for="item in wayList" :label="item" :key="item" class="mr20"></el-checkbox>
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="flag = false" class="cancelButton">取 消</el-button>
        <el-button type="primary" @click="checked" class="searchButton">提交</el-button>
      </span>
    </el-dialog>

    <el-dialog title="使用模板" v-loading="templateLoading" :visible.sync="useTempDialogVisible" :close-on-click-modal="false">
      <div>
        <div class="flex">
          <el-form :inline="true" :model="dataForm" size="mini" ref="dataForm" :rules="dataFormRules">
            <el-form-item label="活动类型：" class="w178">
              <el-select v-model="dataForm.promType" disabled>
                <el-option label="秒杀" :value="Number(2)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="id" label="ID：" class="w178">
              <el-input v-model="dataForm.id" clearable></el-input>
            </el-form-item>
            <el-form-item prop="templateName" label="名称：" class="w178">
              <el-input v-model="dataForm.templateName" clearable maxlength="80"></el-input>
            </el-form-item>
          </el-form>
          <el-row class="t_r mb30">
            <kt-button
              icon="el-icon-search"
              :label="'搜索'"
              @click="tempPageQuery"
              class="searchButton"
            />
          </el-row>
        </div>
        <div>
          <div class="tab-container">
            <el-table
              :data="tableData"
              :highlight-current-row="true"
              :max-height="1500"
              :size="size"
              align="center"
            >
              <el-table-column prop="id" label="ID" align="center"></el-table-column>
              <el-table-column align="center" prop="promType" label="活动类型">
                <template slot-scope="scope">
                  <span v-if="scope.row.promType == 4">秒杀</span>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="templateName" label="模板名称"></el-table-column>
              <el-table-column align="center" prop="creatorName" label="创建人"></el-table-column>
              <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
              <el-table-column align="center" fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button @click="used(scope.row)" type="text" class="textButton" size="small">使用</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="toolbar t_r" v-if="tableData.length > 0">
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="handleCurrentChangeForTemplate"
                :current-page="dataForm.limit"
                :page-size="dataForm.start"
                :total="templateTableDataSize"
                :page-sizes="[10, 20, 30, 40]"
                @size-change="handleSizeChangeForTemplate"
              ></el-pagination>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import marketRequest from "@/market/request/marketRequest";
import { front_prom_types, chanel_codes } from "@/market/dict/marketDict";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { darkmagenta } from "color-name";
import tabPane from "./components/TabPaneSkillPromotion";
export default {
  name: "Tab",
  components: {
    tabPane,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    var checkStartTime = (rule, value, callback) => {
      if (value == null || typeof value == "undefined") {
        callback();
      }
      if (
        this.filters.endTime == null ||
        typeof this.filters.endTime == "undefined"
      ) {
        callback();
      }
      if (
        new Date(value).getTime() > new Date(this.filters.endTime).getTime()
      ) {
        callback(new Error("开始时间不能大于结束时间"));
      }
      this.$refs.filters.clearValidate("endTime");
      callback();
    };
    var checkEndTime = (rule, value, callback) => {
      if (value == null || typeof value == "undefined") {
        callback();
      }
      if (
        this.filters.startTime == null ||
        typeof this.filters.startTime == "undefined"
      ) {
        callback();
      }
      if (
        new Date(value).getTime() < new Date(this.filters.startTime).getTime()
      ) {
        callback(new Error("结束时间不能小于开始时间"));
      }
      this.$refs.filters.clearValidate("startTime");
      callback();
    };
    var checkId = (rule, value, callback) => {
      if (value == null || typeof value == "undefined" || value == "") {
        callback();
      }
      var reg = /^[1-9]\d*$/;
      if (!reg.test(value)) {
        callback(new Error("请输入数字"));
      }
      callback();
    };
    return {
      channelOption:[],
      dataFormRules: {
        //templateName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },
      startDateDisabled: {},//开始时间限制
      endDateDisabled: {},//结束时间限制
      filtersRules: {
        // promName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // creatorNameForSearch: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        startTime: [{ validator: checkStartTime, trigger: "change" }],
        endTime: [{ validator: checkEndTime, trigger: "change" }]
      },
      tableData: [],
      templateTableDataSize: 0,
      dataForm: {
        id: null,
        promType: 4, //满量
        templateName: null,
        limit: 10,
        start: 1
      },
      useTempDialogVisible: false,
      flag: false,
      form: {
        region: ""
      },
      tabMapOptions: [
        { label: "全部", key: "-1" },
        { label: "进行中", key: "5" },
        { label: "已结束", key: "8" },
        { label: "已过期", key: "6" },
        { label: "已关闭", key: "7" },
        { label: "未开始", key: "3" },
        { label: "待提交", key: "1" },
        { label: "待审核", key: "2" },
        { label: "审核未通过", key: "4" },
        { label: "活动草稿", key: "9" },

        //{ label: "审核通过", key: "11" },
      ],
      activeName: "-1",
      createdTimes: 0,
      size: "small",
      templateLoading:false,
      filters: {
        promName: null,
        promotionCode: null,
        id: "",
        promType: 4, //秒杀
        frontPromType: "",
        channelCode: "",
        activityType: "",
        merchantId: "",
        creatorNameForSearch: null,
        startTime: "",
        endTime: "",
        storeId: "",
        type: "",
        t: "sysConfig",
        queryname: "",
        promotionCode: '',
      },
      frontPromTypes: this.getFrntPromType(),
      channelCodes: chanel_codes,
      activityTypes: [
        { activityType: "", label: "请选择" },
        { activityType: "0", label: "自建" },
        { activityType: "1", label: "报名" }
      ],
      merchantIds: [{ storeId: null, label: "请选择" }],
      storeIds: [{ storeId: null, label: "请选择" }],

      joinCheck: [],
      joinList: ["已使用用户", "未使用用户"],
      wayCheck: [],
      wayList: ["短信", "小程序", "网站", "H5", "邮件"]
    };
  },
  methods: {
     queryChannelListOther: function() {
      var this_ = this;
      this.utils.request.queryChannelListOther({}, function(res) {
        if (res.code == "0000") {
          this_.channelOption = res.data;
        }
      });
    },
    changeStartDate: function() {
      var this_ = this;
      this_.endDateDisabled = {
        disabledDate: time => {
          if (this_.filters.startTime) {
            return time.getTime() <= new Date(this_.filters.startTime).getTime();
          }
        }
      };
    },
    changeEndDate: function() {
      var this_ = this;
      this_.startDateDisabled = {
        disabledDate: time => {
          if (this_.filters.endTime) {
            return time.getTime() >= new Date(this_.filters.endTime).getTime();
          }
        }
      };
    },
    handleSizeChangeForTemplate(pageNum) {
      this.dataForm.limit = pageNum;
      this.tempPageQuery();
    },
    handleCurrentChangeForTemplate(pageSize) {
      this.dataForm.limit = 1;
      this.dataForm.start = pageSize;
      this.tempPageQuery();
    },
    // 使用模板
    useTemp() {
      this.tableData = [];
      this.useTempDialogVisible = true;
      this.tempPageQuery();
    },
    // 使用模板，使用的时候先复制再跳转
    used(row) {
      this.utils.request.skillCopyConfig(
        { promotionId: row.promotionId },
        res => {
          if (res.code == "0000") {
            this.couponTemplatedialogVisible = false;
            this.$router.push({
              path: "/SeckillPromotionAdd/"+res.data + "/0/1"
            });
          } else {
            this.$message({ message: res.msg, type: "error" });
          }
        }
      );
    },
    // 分页查询
    tempPageQuery() {
      this.templateLoading = true;
      let callback = res => {
        this.templateLoading = false;
        if (res.code == "0000") {
          this.tableData = res.data.rows;
          this.templateTableDataSize = res.data.total;
        } else {
          this.$message({ message: "查询失败", type: "fail" });
        }
      };
      this.utils.request.templatePageQuery(this.dataForm, callback);
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    getFrntPromType: function(row, column, cellValue, index) {
      return front_prom_types.filter(e => {
        return e.code == "sigle_front_prom_type_ml";
      });
    },

    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
      }
      this.$refs.child[0].listQuery.pageNo = 1;
      this.$refs.child[0].getList();
    },
    createPage() {
      // this.$router.push("/CreatePromotion3");
      this.$router.push("/SeckillPromotionAdd/0/1/1");
    },
    getPromotionList() {
      this.$refs.child[0].listQuery.pageNo = 1;
      this.$refs.child[0].getList();
    },
    changeMerchant() {
      let this_ = this;
      this.utils.request.queryStoreList(
        { start: 1, limit: 10000000, merchantId: this.filters.merchantId },
        function(res) {
          if (res.code == "0000") {
            res.data.rows.forEach(item => {
              //,{'storeId':'0','label':'张小二bbc店铺'},{'storeId':'1','label':'张小二的京东店'}
              let store = {};
              store.storeId = item.id;
              store.label = item.storeName;
              this_.storeIds.push(store);
            });
          }
        }
      );
    },
    checked() {
      this.flag = false;
      if (this.form.region == "one") {
        this.$router.push("/SeckillPromotionEvent" + "?auth=0");
      } else if (this.form.region == "two") {
        this.$router.push("/GroupActivityComponents?auth=0");
      } else {
        this.$router.push("/CreatePromotion3");
      }
    },
    SecondSell() {
      this.flag = true;
    }
  },
  watch: {
    activeName(val) {
      this.$router.push(`${this.$route.path}?tab=${val}`);
    }
  },
  created() {
    //获取商家列表
    let this_ = this;
    // this.utils.request.queryMerchantList(
    //   { start: 1, limit: 10000000 },
    //   function(res) {
    //     if (res.code == "0000") {
    //       res.data.rows.forEach(item => {
    //         let merchant = {};
    //         merchant.merchantId = item.id;
    //         merchant.label = item.name;
    //         this_.merchantIds.push(merchant);
    //       });
    //     }
    //   }
    // );
    //this.changeMerchant();
    // init the default selected tab
    //this.frontPromTypes = front_prom_types;
    const tab = this.$route.query.tab;
    if (tab) {
      this.activeName = tab;
    }
  },
  mounted() {
   // this.queryChannelListOther()
  }
};
</script>

<style scoped lang="scss">
  /deep/ .el-tabs--card>.el-tabs__header .el-tabs__item:first-child{
    border-left: 1px solid #9B9DA3 !important;
    &.is-active {
      border-color: #0090FF !important;
    }
  }
</style>
